package com.house.service.house;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.jws.Oneway;
import java.io.File;
import java.io.InputStream;

/**
 * @author:lzq
 * @date: 2018/6/13 16:15
 */
@Service
public class QiniuServiceImpl implements IQiniuService,InitializingBean{

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private BucketManager bucketManager;

    @Autowired
    private Auth auth;

    @Value("${qiniu.Bucket}")
    private String bucket;

    private StringMap putPolicy;

    @Override
    public Response uploadFile(File file) throws QiniuException {
         Response response= this.uploadManager.put(file,null,getUploadToken());
         //如果上传失败，retry
        int retry=0;
        while (response.needRetry()&&retry<3){
            response= this.uploadManager.put(file,null,getUploadToken());
            retry++;
        }
        return response;
    }

    @Override
    public Response uploadFile(InputStream inputStream) throws QiniuException {
        Response response=this.uploadManager.put(inputStream,null,getUploadToken(),null,null);
        int retry=0;
        while (response.needRetry()&& retry<3){
            response=this.uploadManager.put(inputStream,null,getUploadToken(),null,null);
        }
        return response;
    }

    @Override
    public Response deleteFile(String key) throws QiniuException {
        Response response=this.bucketManager.delete(this.bucket,key);
        int retry=0;
        while (response.needRetry()&& retry<3){
            response=this.bucketManager.delete(this.bucket,key);
        }
        return response;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.putPolicy=new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
    }

    /**
     * 获取七牛云上传token
     * @return
     */
    public String getUploadToken(){
        return this.auth.uploadToken(bucket,null,3600,putPolicy);
    }
}
